import axios from 'axios';
import React, { useEffect, useMemo, useState, useRef } from 'react'
import { Checkbox, Button } from 'antd-mobile'
import { Dialog, List, SwipeAction } from 'antd-mobile'

export default function Shopping() {
  const [cartList, setCartList] = useState([]);
  const ref = useRef(null);
  const [isChecked, setisChecked] = useState(true);
  let {username, password} = JSON.parse(localStorage.getItem('token'));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(()=>{
    axios(`/carts?password=${password}&username=${username}&_expand=good`).then(res => {
      console.log(res.data)
      setCartList(res.data);
      res.data.forEach(item => {
        if(item.checked === false)
          setisChecked(false);
      })
    })
  },[username, password]);
  const handlecheck = (value, item) =>{
    item.checked = !item.checked;
    setCartList(cartList.map(data =>{
      if(data.id === item.id)
        return item;
      else
        return data;
    }))
    axios.patch(`/carts/${item.id}`,{
      checked:value
    })
  }
  let computedtotal = useMemo(()=>{
    let total = 0;
    cartList.forEach(item =>{
      if(item.checked){
        total += item.good.price * item.number;
      }
    })
    return total;
  },[cartList]);
  const handleAllcheck = (value) =>{  //用全选框控制单品框
    let v = value;
    setisChecked(v);
    setCartList(cartList.map(item =>{
      item.checked = v;
      return item;
    }))
    cartList.forEach(item=>{
      axios.patch(`/carts/${item.id}`,{checked:v})
    })
  }
  const allofchecked = () =>{  //用单选框控制全选框
      let v = cartList.every(item => 
        item.checked === true
      )
    setisChecked(v);
  }
  const addnumber = (item) =>{
    item.number = item.number + 1;
    setCartList(cartList.map(data => {
      if(data.id === item.id)
        return item;
      else{
        return data;
      }
    }))
  }
  const reducenumber = (item) =>{
    item.number = item.number - 1;
    setCartList(cartList.map(data => {
      if(data.id === item.id)
        return item;
      else{
        return data;
      }
    }))
  }
  return (
    <div style={{backgroundColor:'#edeae7', height: '100vh', paddingBottom:'3.0625rem'}}>
      <h2 style={
        {
          backgroundColor:'#009be2', 
          height:'3rem', 
          lineHeight:'3rem', 
          textAlign:'center', 
          color:'white', 
          fontWeight:'bold',
          position:'fixed',
          width:'100%',
          top:'0',
          zIndex:10,
          borderRadius:'0 0 .5rem .5rem'
        }
      }>{username}的购物袋</h2>
      <div style={{overflow:'auto', height:'100%', paddingTop:'3.0125rem', paddingBottom:'3.0125rem'}}>
        {
          cartList.map((item) => 
            <List key={item.good.id} 
                style={
                  {
                    margin:'.5rem .5rem', 
                    padding:'.5rem .5rem', 
                    backgroundColor:'white', 
                    borderRadius:'1rem',
                    overflow:'auto'
                  }
              }>
              <SwipeAction
                ref={ref}
                closeOnAction={false}
                closeOnTouchOutside={false}
                rightActions={[
                  {
                    key: 'delete',
                    text: '删除',
                    color: 'danger',
                    onClick: async () => {
                      const result = await Dialog.confirm({
                        content: '确定要删除吗？',
                      })
                      if (result) {
                        setCartList(cartList.filter(data => 
                          data.id !== item.id
                        ))
                        axios.delete(`/carts/${item.id}`);
                        window.location.reload();
                      }
                      ref.current?.close()
                    },
                  },
                ]}
              >
                <List.Item>
                  <div style={
                    {
                      display:'flex',
                      justifyContent:'space-around',
                      alignItems:'center'
                    }
                  }>
                    <Checkbox 
                      checked = {item.checked}
                      onChange={(value)=>{
                        handlecheck(value, item);
                        allofchecked();
                      }}
                      />
                    <img src={`http://localhost:5000/${item.good.poster}`} alt='加载失败' style={{width:'5rem', height:'6rem'}} />
                    <div style={{flex:'1', paddingLeft:'.3rem'}}>
                      <div style={{fontSize:'1.1rem'}}>{item.good.title}</div>
                      <div style={{fontSize:'1.05rem', color:'red'}}>￥{item.good.price}</div>
                    </div>
                    <div style={{display:'flex', border:'1px solid black', borderRadius:'.5rem', width:'4rem', justifyContent:'space-around'}}>
                      <button style={{border:'none', backgroundColor:'transparent'}} disabled={item.number===1? 1:0} onClick={()=>{
                        reducenumber(item);
                      }}>-</button>
                      <div style={{borderRight:'1px solid black', borderLeft:'1px solid black', padding:'0 .5rem'}}>{item.number}</div>
                      <button style={{border:'none', backgroundColor:'transparent'}} onClick={()=>{
                        addnumber(item);
                      }}>+</button>
                    </div>
                  </div>
                </List.Item>
              </SwipeAction>
            </List>
        )}
      </div>
      <div style={
        {
          backgroundColor:'white', 
          height:'3.0625rem',
          width:'100%',
          position:'fixed', 
          bottom:'3.0625rem',
          display:'flex',
          justifyContent:'space-around',
          alignItems:'center',
          padding:'0 1rem'
        }
      }>
        <Checkbox  checked={isChecked} style={{flex:'1'}} onChange={(value)=>{
          handleAllcheck(value);
        }}>全选</Checkbox>
        <span style={{marginRight:'1rem'}}>合计:<span style={{fontSize:'1.5rem', color:'red'}}> {computedtotal} </span>元</span>
        <Button
            style={{
              height:'2.2rem',
            }}
            color='primary'
            onClick={() => {
              alert('hello.')
            }}
        > 结算 </Button>
      </div>
    </div>
  )
}
